/**
 * 
 */
package com.et.mvc.easy;

import java.util.HashMap;
import java.util.Iterator;

import com.et.mvc.Controller;
import com.et.mvc.Dispatcher;
import com.et.mvc.FreeMarkerView;
import com.et.mvc.filter.BeforeFilter;

/**
 * <p>集成freemarker封装基类</p>
 * @author defier Lai
 * <p>Date: 2009-10-31 上午01:27:17</p>
 * @version 1.0
 */
@BeforeFilter(execute="setResourcePath")
public class EasyController extends Controller {

	private FreeMarkerView defaultView ;
	
	/**
	 * 设置资源默认路径信息，在freemarker页面上直接调用，所有子类控制器必须继承此控制器
	 * @return
	 */
	protected boolean setResourcePath() {
		initViews();
		defaultView.setAttribute("base", request.getContextPath());
		defaultView.setAttribute("resource", request.getContextPath()+"/public");
		defaultView.setAttribute("images", request.getContextPath()+"/public/themes/"+ getDefaultStyle() +"/images");
		defaultView.setAttribute("stylesheets", request.getContextPath()+"/public/themes/"+ getDefaultStyle() +"/stylesheets");
		defaultView.setAttribute("javascripts", request.getContextPath()+"/public/themes/"+ getDefaultStyle() +"/javascripts");
		return true;
	}

	/**
	 * 重置页面模板路径与页面引擎
	 */
	private void initViews() {
		defaultView = new FreeMarkerView();
		setViewsBasePath();
	}

	/**
	 * 设置模板根目录
	 */
	private void setViewsBasePath() {
		Dispatcher.setViewBasePath("/views/"+getDefaultStyle());
	}
	
	/**
	 * 获取当前系统的页面风格，如果需要支持多风格，更换风格时，只要调用setDefaultStyle(String style)方法即可
	 * @return
	 */
	protected String getDefaultStyle() {
		Object style = defaultView.getAttributes().get("defaultStyle");
		if(style != null) {
			return (String)style;
		}
		return "default";
	}
	
	protected void setDefaultStyle(String style) {
		defaultView.setAttribute("defaultStyle", style);
		setViewsBasePath();
	}

	public FreeMarkerView getDefaultView() {
		return defaultView;
	}

	/**
	 * defaultVie必须与风格对应的文件夹名称一致
	 * @param defaultView
	 */
	public void setDefaultView(FreeMarkerView defaultView) {
		this.defaultView = defaultView;
	}
	
	/**
	 * 设置输出数据
	 * @param key
	 * @param value
	 */
	protected void render(String key, Object value) {
		getDefaultView().setAttribute(key, value);
	}
	
	protected void render(Object[]... values) {
		for(Object[] o : values) {
			if(o != null && o.length == 2) {
				render(String.valueOf(o[0]), o[1]);
			} else {
				throw new IllegalArgumentException("params is error, please check ["+values+"]");
			}
		}
	}
	
	protected void render(HashMap<String, Object> values) {
		Iterator<?> it = values.entrySet().iterator();
		while(it.hasNext()) {
			String key = (String) it.next();
			render(key, values.get(key));
		}
	}
	
}
